#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import db
from bz2 import compress, decompress
from GPXTimeline import GPXTimeline
from google.appengine.api import users

def getTrack(key):
  if users.GetCurrentUser():
    return db.get(db.Key(key))
  else:
    return None
def putTrack(track):
  track.album =  "http://picasaweb.google.com/data/feed/api/user/%s/album/%s?kind=photo" % (
    track.albumOwner,track.albumName)
  track.put()
  return

class Track(db.Model):
  id = db.Key()
  user = db.UserProperty()
  # N.B. name may be unicode, use name.encode('ascii') if
  # value must be ASCII endoded, e.g. when used in HTTP headers.
  name = db.StringProperty()
  content = db.BlobProperty()
  date = db.DateTimeProperty(auto_now_add=True)
  isStartTime = db.BooleanProperty()
  geoStart = db.GeoPtProperty()
  album = db.LinkProperty()
  albumOwner = db.StringProperty()
  albumName = db.StringProperty()
  timeSlip = db.IntegerProperty()
  isPublic = db.BooleanProperty()

  def getContent(self):
    return decompress(self.content)

  def getStartDatetime(self):
    if True:
    #try:
      if self.isStartTime == False:
        timeline = GPXTimeline().timeline(self.getContent())
        (firstSegStart, firstSegEnd) = timeline[0] 
        self.date = firstSegStart.when
        self.geoStart = "%f,%f" % (firstSegStart.lat, firstSegStart.lon)
        self.isStartTime = True
        self.put()
      pass
    else:
    #except:
      self.isStartTime = False
      pass
    return self.date

  def getStartDatetimeStr(self,fmt="%b %d %Y %H:%M"):
    return self.getStartDatetime().strftime(fmt)


